package com.lagou.config;

import com.lagou.enums.SqlCommandTypeEnum;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: lcz
 * @date: Created in 14:12 2020/9/25
 * @description:
 */
public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * @author: lcz
     * @date: Created in 14:14 2020/9/25
     * @description: 解析mapper.xml文件
     */
    public void parse(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);
        //获取根节点
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        //获取子节点select/insert/update/delete
        List<Element> elementList = rootElement.selectNodes("select|insert|update|delete");
        for (Element element : elementList) {
            String id = element.attributeValue("id");
            String sql = element.getTextTrim();
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            Class<?> resultTypeClass = getClassType(resultType);
            Class<?> parameterTypeClass = getClassType(parameterType);

            //封装mappedStatement对象
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultTypeClass);
            mappedStatement.setParameterType(parameterTypeClass);
            mappedStatement.setSql(sql);
            mappedStatement.setSqlCommandType( SqlCommandTypeEnum.valueOf(element.getName().toUpperCase()));

            //statementId
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }

    /**
     * @author: lcz
     * @date: Created in 14:22 2020/9/25
     * @description: 根据名称获取class类
     */
    private Class<?> getClassType(String className) throws ClassNotFoundException {
        if (StringUtils.isEmpty(className)) {
            return null;
        }
        return Class.forName(className);
    }
}
